package com.yixun.qfbao.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.utils.TokenUtils;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class CheckTokenInterceptor {
    @Autowired
    TokenUtils tokenUtils;
    @Pointcut("@annotation(com.yixun.qfbao.annotations.CheckToken)")
    public void pointcut() { }

    @Around("pointcut() && args(request,..)")
    public Object addApiLog(ProceedingJoinPoint pjp, HttpServletRequest request)throws Throwable{
        Object[]  methodParam = pjp.getArgs();
        JSONObject jsonObject =  JSONObject.parseObject(JSONObject.toJSONString(methodParam[1]));
        JSONObject o = jsonObject.getJSONObject("params");
        Object token = o.get("token").toString();
        Object companyUuid = o.get("companyUuid").toString();
        BaseResponseDTO baseResponseDto = new BaseResponseDTO();
        if(token == null ){
            baseResponseDto.setResult(ResultEnum.FAIL.getNo());
            baseResponseDto.setErrorMsg("token 为空");
            return JSONObject.toJSONString(baseResponseDto);
        }
        if(companyUuid == null){
            baseResponseDto.setResult(ResultEnum.FAIL.getNo());
            baseResponseDto.setErrorMsg("companyUuid 为空");
            return JSONObject.toJSONString(baseResponseDto);
        }

        if(!tokenUtils.checkToken(token.toString(),companyUuid.toString())){
            baseResponseDto.setResult(ResultEnum.TOKEN_INVALID.getNo());
            baseResponseDto.setErrorMsg("token 无效");
            return JSONObject.toJSONString(baseResponseDto);
        }

        Object returnObject = pjp.proceed();
        return returnObject;
    }
}
